<?php
/**
 * Created by PhpStorm.
 * Author: Akon
 * Date: 2016/11/29 0029
 * Time: 22:45
 * 后台登录控制器
 */
namespace Manager\Controller;
use Think\Controller;
use Think\Verify;

class AdminController extends Controller{

    /**管理员登录**/
    public function login(){
        if(IS_POST){
            //p(encryptPass("123456"));exit;
            $loginInfo = I("info");
            //1、检查验证码
            $verfiy = $this->check_verify($loginInfo['verfiy']);
            if(!$verfiy){
                //exit(json_encode(array('status'=>0,'msg'=>'验证码错误')));
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误'));
            }
            //2、验证用户名和密码
            $condition['username'] = $loginInfo['username'];
            $condition['password'] = encryptPass($loginInfo['password']);
            if(!empty($loginInfo['username']) && !empty($loginInfo['password'])){
                //解密密码
                $pass = decryptPass($loginInfo['password']);
                $pass = encryptPass($pass['password']);
                $res = M("admin")->where(array("username"=>$loginInfo['username'],"password"=>$pass))->find();
                if(is_array($res)){
                    //上一次登录时间
                    $last_login_time = M("admin_log")->where(array("admin_id"=>$res['id'],"admin_info"=>"后台登录"))->order('id desc')->limit(1)->getField("login_time");
                    //更新登录时间和ip
                    M("admin")->where(array("id"=>$res['id']))->save(array("login_time"=>time(),"login_ip"=>getIP(),"login_times"=>$res['login_times'] + 1));
                    //将所需数据存入session,后续使用
                    session("admin_id",$res['id']);
                    session("admin_name",$res['admin_name']);
                    session("last_login_time",$last_login_time);
                    adminLogin("后台登录",__ACTION__);
                    //$url = U('Manager/Index/index');
                    $url = __MODULE__ . "/Index/index";
                    //exit(json_encode(array('status'=>1,'url'=>$url)));
                    $this->ajaxReturn(array("status"=>1,"url"=>$url));
                }else{
                    //exit(json_encode(array('status'=>0,'msg'=>'账号或密码不正确')));
                    $this->ajaxReturn(array("status"=>0,"msg"=>"账号或密码不正确"));
                }
            }
        }else {
            $this->display();
        }
    }

    /**验证码制作**/
    public function vertify(){

        $config = array(
            'fontsize' => 30,
            'length'   => 4,
            'useCurve' => true,
            'useNoise' => false,
            'reset'    => false,
        );
        $Verify = new Verify($config);
        $Verify->entry();
    }
    /**验证验证码**/
    function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }
    /**退出登录**/
    function login_out(){
        session_unset();
        session_destroy();
        $this->success("退出成功",U("Manager/Admin/login"));
    }


}

